"use strict";
define(["commonUI", "getTime","global", "laydate", "template","datatables","select2"], function (
    commonUI, getTime,global, laydate ,template,
) {

    //当前项目
    var project=null;
    //当前登录用户
    var user=null;

    var deviceId2deviceName = null;
    
    function initDeviceSelect(deviceId){
        //初始化采集点选择项(弹窗中)
        global.get("/web/device/devicesByProject/"+project.id,function(response){
            if(response.success){
                var devices = response.data.devices;
                $("#name").empty()
                console.log(deviceId)
                devices.forEach(function(device){
                    if(deviceId == device.id){
                        $("#name").append("<option selected value="+device.id+">"+device.name+"</option>")
                    }else{
                        $("#name").append("<option value="+device.id+">"+device.name+"</option>")
                    }
                })
            }
        })
    }

    /**
     * 补录数据
     */
    function saveOrUpdate(){
        if($("#time").val() ==null || $("#time").val().trim() == "" ){
            alert("采集时间不能为空");
            return;
        }
        if($("#data1").val() ==null || $("#data1").val().trim() == "" ){
            alert("原有数值不能为空");
            return;
        }
        if($("#data2").val() ==null || $("#data2").val().trim() == "" ){
            alert("补录数值不能为空");
            return;
        }
        var data = {
            id:$("#id").val(),
            deviceId:$("#name").val(),
            createTime:$("#time").val(),
            //原有数据  data
            data:$("#data1").val(),
            //补录数据  modifiedData
            modifiedData:$("#data2").val()
        }
        global.post("/web/dataSupply/saveOrUpdate/"+data.deviceId,function(response){
            if(response.success){
                Dialog.toast(response.message, {"intent":"success"});
                standardTable.ajax.reload();
            }else{
                Dialog.toast(response.message, {"intent":"warn"});
            }
        },JSON.stringify(data))
    }
    var standardTable;
    var param = {
        pageNumber: 1,
        pageSize: 10
    };
    var app = {
        init: function () {
            if(!global.existCurrProject()){
                alert("请先选择项目");
                return;
            }
            project = global.getCurrProject();
            user = global.getLoginUser();
            this.eventBind();
            // getTime.resize();
            this.initText();
            getTime.getNowDate();
            getTime.getTimeInfo();
            this.initSelect();
            this.initTimeSelect();
            
        },
        /**
        * 渲染文字内容
        */
        initText :function() {
            user = global.getLoginUser();
            //用户名显示
            $(".name").text(user.userName)
        },
        initSelect:function(){
            global.get("/web/device/devicesByProject/"+project.id,function(response){
                if(response.success){
                    deviceId2deviceName = new Map();
                    var devices = response.data.devices;
                    var data = [];
                    devices.forEach(function(device){
                        data.push({
                            id:device.id,
                            text:device.name
                        });
                        deviceId2deviceName.set(device.id,device.name)
                    });
                    $("#deviceId").empty()
                    $("#deviceId").select2({
                        width:200,
                        data:data
                    })
                    // $("#deviceId").empty()
                    // devices.forEach(function(device){
                    //     $("#deviceId").append("<option value="+device.id+">"+device.name+"</option>")
                    // });
                    // $("#deviceId").select2({
                    //     width: 200,
                    //     placeholder: "请选择点位",
                    //     ajax: {
                    //         url:"/web/device/devicesByProject/"+project.id, // 下拉搜索接口
                    //         type: 'get',
                    //         dataType: 'json',
                    //         delay: 250,
                    //         data: function(params){
                    //             // params.term 表示输入框中内容，
                    //             // name表示发送到服务器的参数，
                    //             // 此处也可以增加其他需要传递给服务器的参数
                    //             return {
                    //                 keyword: params.term // 搜索参数
                    //             }
                    //         },
                    //         processResults: function(data,params){
                    //             // 返回最终数据给results
                    //             // 此处可以做一些适配操作，比如获取的数据在data.res下则返回data.res
                    //             console.log(data)
                    //             var list = data.device.map(function(v,i) {
                    //                 v.text = v.name
                    //                 return v;
                    //             })
                    //             return {
                    //                 results: data
                    //             }
                    //         }
                    //     },
                    //     // 至少输入几个字符开始查询
                    //     minimumInputLength: 0
                    // })
                    app.initTable();
                }
            })
            
        },
        // 搜索条件初始化
        initTimeSelect: function () {
            var start = laydate.render({
                elem: '#beginTime',
                showBottom: false,
                eventElem: '.layout-icon-1',
                trigger: 'click',
                // max: 0,
                done: function (value, date, endDate) {
                    end.config.min = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    };
                    end.config.value = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; //将结束日的初始值设定为开始日
                }
            });
            //结束时间
            var end = laydate.render({
                elem: '#endTime',
                showBottom: false,
                eventElem: '.layout-icon-2',
                trigger: 'click',
                // max: 0,
                done: function (value, date) {
                    start.config.max = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; //结束日选好后，重置开始日的最大日期
                }
            })
        },
        // 表格初始化
        initTable: function () {
            standardTable = $("#standard_table").DataTable({
                // 关闭搜索功能
                processing: true,
                searching: false,
                serverSide: true,
                destroy: true,
                ordering: false,
                // scrollY: 600,
                // scrollCollapse: true,
                columns: [{
                    title: "序号",
                    data: "number",
                    width: "100px",
                    render: function (data, type, full) {
                        return "<div class='rank'>" + data + "</div>";
                    }
                }, {
                    title: "点位名称",
                    data: "deviceName",
                    width: "20%"
                },{
                    title: "时间",
                    data: "createTime",
                    width: "240px",
                    render: function (data, type, full) {
                        return "<div class=\"text-overflow\" title=\"" + data + "\"><i class='aidicon aidicon-timetable'></i>" + data + "</div>";
                    }
                },{
                    title: "补录时间",
                    data: "modifiedTime",
                    width: "240px",
                    render: function (data, type, full) {
                        if(data == null){
                            return "未补录";
                        }
                        return "<div class=\"text-overflow\" title=\"" + data + "\"><i class='aidicon aidicon-timetable'></i>" + data + "</div>";
                    }
                }, {
                    title: "原有数值",
                    data: "data",
                    width: "20%"
                }, {
                    title: "补录数值",
                    data: "modifiedData",
                    width: "20%",
                    render:function(data, type, full){
                        if(full.isModified){
                            return data;
                        }else{
                            return "未补录";
                        }
                    }
                }, {
                    title: "单位",
                    data: "unit",
                    width: "20%"
                }, {
                    title: "操作",
                    width: "150px",
                    render: function (data, type, full, meta) { //其中data代表本列数据，full代表本行所有数据
                        return '<button type="button" class="btn btn-warning btn-sm editData" name="'+full.deviceId+'" time="'+full.createTime+'" data1="'+full.data+'" data2="'+full.modifiedData+'" id="'+full.id+'" deviceId="'+full.deviceId+'">补录</button>';
                    }
                }],
                columnDefs: [{
                    // targets 同时制定多个列时，可以传递数组（比如[1,2]）;制定所有传"_all"  
                    targets: [1, 3, 4, 5],
                    render: function (data, type, full, meta) { //其中data代表本列数据，full代表本行所有数据
                        return "<div class=\"text-overflow\" title=\"" + data + "\">" + data + "</div>";
                    }
                }],
                language: {
                    sEmptyTable: "<div class=\"blank-icon\"><p class=\"msg\"><i class=\"aidicon aidicon-emoticon-sad\"></i> 没有搜到任何数据</p></div>"
                },
                ajax: function (params, callback, setting) {
                    // param.pageNumber = (params.start / params.length) + 1;
                    // param.pageSize = params.length;
                    // param.startTimeSearch = $("#beginTime").val();
                    // param.endTimeSearch = $("#endTime").val();
                    // param.keySearch = $("#optUser").val();
                    // param.projectId = project.id;
                    // global.get("/web/dataSupply/listAllByProject",function (res) {
                    //     if (res.success) {
                    //         var obj = {};
                    //         obj.data = res.data.page.content;
                    //         obj.draw = params.draw;
                    //         obj.recordsTotal = res.data.page.totalElements;
                    //         obj.recordsFiltered = res.data.page.totalElements;
                    //         callback(obj);
                    //         }
                    //     },param);

                    param.pageNumber = (params.start / params.length) + 1;
                    param.pageSize = params.length;
                    param.startTimeSearch = $("#beginTime").val();
                    param.endTimeSearch = $("#endTime").val();
                    param.deviceId = $("#deviceId").val();
                    param.projectId = project.id;
                    global.get("/web/dataSupply/listAllByProject1",function (res) {
                        if (res.success) {
                            var obj = {};
                            obj.data = res.data.page.content;
                            obj.draw = params.draw;
                            obj.recordsTotal = res.data.page.totalElements;
                            obj.recordsFiltered = res.data.page.totalElements;
                            callback(obj);
                            }
                        },param);
                },
                initComplete: function (settings, json) {

                }
            });
        },
        /** 事件绑定 */
        eventBind: function () {
            //搜索按钮
            $(document).on("click", "#searchBtn", function () {
                standardTable.ajax.reload();
            })
            $(document).on("click","#exportTable",function(){
                // 采集点ID
                // 开始时间
                // 结束时间
                // 采集点名称
                let beginTime = $("#beginTime").val();
                let endTime = $("#endTime").val();
                if(beginTime == null || beginTime == "" || endTime == null || endTime == ""){
                    Dialog.toast("请选择时间范围", {"intent":"warn"});
                    return;
                }
                if(beginTime > endTime){
                    Dialog.toast("开始时间早于结束时间", {"intent":"warn"});
                    return;
                }
                let deviceId = $("#deviceId").val()
                let projetName = project.name;
                let deviceName = deviceId2deviceName.get(parseInt(deviceId))
                Dialog.confirm(`请问确定是否导出<span style='color:red'>${projetName}</span>采集点位<span style='color:red'>${deviceName}</span>在<span style='color:red'>${beginTime}</span>到<span style='color:red'>${endTime}</span>之间数据？<br><br><span style='color:red'>导出报表可能会花费较长时间，请耐心等待。</span>`, function(){
                    // alert("确认");
                    location.href = `${global.baseUrl}/web/dataSupply/exportTable?deviceId=${deviceId}&beginTime=${beginTime}&endTime=${endTime}`
                },function(){
                    // alert("取消");
                });
            })
            // 新增弹窗
            $(document).on("click", "#addData", function () {
                initDeviceSelect();
                Dialog.open({
                    title: "新增",
                    theme: "formDialog",
                    width: 480,
                    height: 400,
                    context: self,
                    content: template("dataFormTpl",{data1:0}),
                    onShow: function () {
                        laydate.render({
                            elem:'#time',
                            type:'datetime',
                            eventElem: '.icon1', // 点击 icon1 显示
                            trigger: 'click'
                        })
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            saveOrUpdate();
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            $(document).on("change","#deviceId",function(){
                app.initTable();
            })
            // 编辑弹窗
            $(document).on("click", ".editData", function () {
                initDeviceSelect($(this).attr("deviceId"));
                var data = {};
                data.id=$(this).attr("id")
                data.name = $(this).attr("name");
                data.time = $(this).attr("time");
                data.data1 = $(this).attr("data1");
                data.data2 = $(this).attr("data2");
                Dialog.open({
                    title: "补录",
                    theme: "formDialog",
                    width: 480,
                    height: 400,
                    context: self,
                    content: template("dataFormTpl",data),
                    onShow: function () {
                        laydate.render({
                            elem:'#time',
                            type:'datetime',
                            eventElem: '.icon1', // 点击 icon1 显示
                            trigger: 'click'
                        })
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            saveOrUpdate();
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ]
                });
            })
            window.onresize = function () {
                // getTime.resize();
            };
        },

    };
    return app;
});